package org.huqiwen.blog.control;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.huqiwen.blog.logic.MessageLogicBean;

public class MessageActionServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String method = (String) request.getParameter("method");
		if (method == null) {
			PrintWriter out = response.getWriter();
			out.println("无效请求");
		} else if (method.equals("addMessage")) {
			AddMessage(request, response);
		} else if (method.equals("delMessage")) {
			DelMessage(request, response);
		}
	}

	protected void AddMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String title = request.getParameter("title");
		String name = request.getParameter("name");
		String content = request.getParameter("content");
		String messageIP = request.getRemoteAddr();
		int result = new MessageLogicBean().addMessage(title, name, content,
				messageIP);
		if (result == 1) {
			response.sendRedirect("Message.jsp?curPage=1");
			// request.getRequestDispatcher("Message.jsp?curPage=1").forward(request,
			// response);
		} else {
			request.getRequestDispatcher("error.jsp")
					.forward(request, response);
		}
	}

	protected void DelMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String messageId = request.getParameter("id");
		int result = new MessageLogicBean().delMessage(messageId);
		if (result == 1) {
			response.sendRedirect("Message.jsp");
		} else {
			response.sendRedirect("error.jsp");
		}
	}
}
